<template>
  <van-image lazy-load @click="showImg()" :src="img || (!img_loading && noIMg)" :class="[$attrs.class, className]" class="preimg" fit="cover" :show-loading="true" />

  <van-image-preview v-model:show="show" :images="[img]"></van-image-preview>
</template>

<script setup lang="ts">
import { getPicById } from '@/api/common'
import noIMg from '@/assets/img/no-img.svg'
let $attrs = useAttrs()
const show = ref(false)
const props = defineProps({
  data: { type: [Object, String], default: () => null },
  imgProp: { type: String, default: 'id' },
  preView: { type: Boolean, default: true },
  className: { type: String, default: '' }
})
//处理展示的数据，因为后端返回的图片可能是一个对象集合，根据图片key，取出对应的数据
const img = ref<any>()
const img_loading = ref(false)
const getImg = (val: any) => {
  let imgid = val[props.imgProp]
  if (imgid) {
    img_loading.value = true
    getPicById({ id: imgid })
      .then(res => {
        img.value = res.base64Str
      })
      .finally(() => {
        img_loading.value = false
      })
  }
}
watch(
  () => props.data,
  val => {
    if (val) {
      img.value = ''
      getImg(val)
    }
  },
  { immediate: true, deep: true }
)
//预览对应的图片
const showImg = () => {
  if (!props.preView) {
    return
  }
  show.value = true
}
</script>

<style scoped lang="scss">
.preimg {
  width: 100%;
  height: 100%;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
<style>
.imgPreview {
  background: transparent;
}
</style>
